import {
  getListUserApi,
  getRoleAllApi,
  addUserRoleRelationApi,
  getRoleByUserIdApi,
  ftmFleetFindAllApi,
  findListByFleetApi
} from '@/services/users.js';

import { message } from 'ant-design-vue';
export default {
  namespaced: true,
  state: {
    userListLoading: false,
    userList: [],
    paginationOptions: {
      pageNum: 1,
      pageSize: 10,
      total: 0
    },
    roleAll: [],
    userRoles: {},
    ftmFleetFindAllData: [],
    ftmFleetFindAllLoading: false,
    findListByFleetData: [],
    findListByFleetLoading: false
  },
  mutations: {
    setState(state, { key, payload }) {
      state[key] = payload;
    }
  },
  actions: {
    // 获取用户list
    async getListUser({ state, commit }, params) {
      commit('setState', { key: 'userListLoading', payload: true });
      const { pageNum, pageSize } = state.paginationOptions;
      const apiParams = {
        pageNum,
        pageSize,
        ...params
      };
      const rep = await getListUserApi(apiParams);
      commit('setState', { key: 'userList', payload: rep.data.list });
      commit('setState', { key: 'paginationOptions', payload: { ...state.paginationOptions, total: rep.data.total }});
      commit('setState', { key: 'userListLoading', payload: false });
    },
    // 所有角色
    async getRoleAll({ state, commit }, params) {
      const rep = await getRoleAllApi();
      commit('setState', { key: 'roleAll', payload: rep.data });
    },
    async getRoleByUserId({ state, commit }, params) {
      const rep = await getRoleByUserIdApi(params);
      commit('setState', { key: 'userRoles', payload: rep.data });
    },
    async ftmFleetFindAll({ commit }) {
      commit('setState', { key: 'ftmFleetFindAllLoading', payload: true });
      const rep = await ftmFleetFindAllApi();
      commit('setState', { key: 'ftmFleetFindAllData', payload: rep.data });
      commit('setState', { key: 'ftmFleetFindAllLoading', payload: false });
    },
    async findListByFleet({ commit }, params) {
      commit('setState', { key: 'findListByFleetLoading', payload: true });
      const rep = await findListByFleetApi(params);
      commit('setState', { key: 'findListByFleetData', payload: rep.data });
      commit('setState', { key: 'findListByFleetLoading', payload: false });
    },
    //  编辑
    async addUserRoleRelation({ commit }, params) {
      commit('setState', { key: 'addLoading', payload: true });
      try {
        const rep = await addUserRoleRelationApi(params);
        if (rep.code === 200) {
          message.success(rep.message);
          return Promise.resolve(true);
        } else {
          message.error(rep.message);
        }
      } catch (error) {
        message.error('操作失败');
      } finally {
        commit('setState', { key: 'addLoading', payload: false });
      }
    }
  }
};
